//
//  UpLoadVC.m
//  doubleEduStudents
//
//  Created by 盛洋 on 2021/1/29.
//  Copyright © 2021 shengYang. All rights reserved.
//

#import "UpLoadVC.h"
#import "upLoadCollectioncellOne.h"
#import "upLoadCollectioncellTwo.h"
#import "upLoadCollectioncellThree.h"
#import "UpLoadImgModel.h"

@interface UpLoadVC ()<UICollectionViewDelegate,upLoadCollectioncellTwoDelegate,TZImagePickerControllerDelegate>
@end

@implementation UpLoadVC{
    UICollectionView *collection_view;
    NSArray *chooseArr;//选择的图片数组
    NSMutableArray *picArr;//选择确认后的图片数组
    NSArray *valuePicArr;//上传照片成功后返回的图片数组
    RequestServices *service;
    NSMutableArray *fileList;//上传的图片url数组
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"上传作品";
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.minimumLineSpacing = 0;
    // 布局方式改为从上至下，默认从左到右
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    // Section Inset就是某个section中cell的边界范围
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 20, 0);
    // 每行内部cell item的间距
    flowLayout.minimumInteritemSpacing = 10;
    // 每行的间距
    flowLayout.minimumLineSpacing = 10;
    collection_view = [[UICollectionView alloc]initWithFrame:CGRectMake(50, 80, SCREEN_W - 100, SCREEN_H - 80)collectionViewLayout:flowLayout];
    collection_view.delegate = self;
    collection_view.dataSource = self;
    collection_view.showsHorizontalScrollIndicator = NO;
    collection_view.showsVerticalScrollIndicator = NO;
    self.view.backgroundColor = collection_view.backgroundColor = [UIColor whiteColor];
    [collection_view registerNib:[UINib nibWithNibName:@"upLoadCollectioncellOne" bundle:nil] forCellWithReuseIdentifier:@"upLoadCollectioncellOne"];
    [collection_view registerNib:[UINib nibWithNibName:@"upLoadCollectioncellTwo" bundle:nil] forCellWithReuseIdentifier:@"upLoadCollectioncellTwo"];
    [collection_view registerNib:[UINib nibWithNibName:@"upLoadCollectioncellThree" bundle:nil] forCellWithReuseIdentifier:@"upLoadCollectioncellThree"];
    [self.view addSubview:collection_view];
    
    picArr = [NSMutableArray array];
    fileList = [NSMutableArray array];
    service = [[RequestServices alloc]initWithDelegate:self];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 1) {
        return picArr.count + 1;
    }
    return 1;
}

//每个item的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        return CGSizeMake(SCREEN_W - 100, SCREEN_H * 0.2);
    }else if (indexPath.section == 1){
        return CGSizeMake((SCREEN_W - 100)/5, 130);

    }else{
        return CGSizeMake(SCREEN_W - 100, 300);
    }
}

//cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        upLoadCollectioncellOne *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"upLoadCollectioncellOne" forIndexPath:indexPath];
        cell.dic = self.valueDic;
        return cell;
    }else if (indexPath.section == 1) {
        upLoadCollectioncellTwo *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"upLoadCollectioncellTwo" forIndexPath:indexPath];
        cell.delegate = self;
        cell.delete_btn.tag = indexPath.item + 2000;
        if (indexPath.row == picArr.count) {
            if (picArr.count > 8) {//最多上传9张 第9张时按钮失效
                [cell.img_btn setUserInteractionEnabled:NO];
            }else{
                [cell.img_btn setUserInteractionEnabled:YES];
            }
            [cell.delete_btn setHidden:YES];
            [cell.img_btn setBackgroundImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];

        }else{
            [cell.delete_btn setHidden:NO];
            [cell.img_btn setUserInteractionEnabled:NO];
            [cell.img_btn setBackgroundImage:picArr[indexPath.item] forState:UIControlStateNormal];
        }
        return cell;
    }else{
        upLoadCollectioncellThree *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"upLoadCollectioncellThree" forIndexPath:indexPath];
        cell.text_view.delegate = self;
        //提交作品
        [cell.tiJiao_btn addTarget:self action:@selector(upLoadFile) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}



#pragma mark ----upLoadCollectioncellTwoDelegate
//添加照片
-(void)choosePicture{
    [self.view endEditing:YES];
    //1.判断相册是否可以打开
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        return;
    }
    
    //解决在6P上选取相册时取消按钮不好点击问题
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9  delegate:self];
    imagePickerVc.delegate = self;
    //是否允许选择视频
    imagePickerVc.allowPickingMultipleVideo = YES;
    //弹出全屏
    imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    //设置导航栏背景色
    CGSize tempNavSize = CGSizeMake(SCREEN_W, STATUSBAR_H+NAVIGATION_H);
    [imagePickerVc.navigationBar setBackgroundImage:[self imageWithColor:Base_lineColor size:tempNavSize] forBarMetrics:UIBarMetricsDefault];
    chooseArr = nil;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if ([photos CheckNSArrayData]) {
//            chooseImg = [DataService compressImageQuality:photos[0] toByte:1024*1024];
//            [self.people_img setImage:self->chooseImg];
            self->chooseArr = [NSArray arrayWithArray:photos];
            [self->picArr addObjectsFromArray:self->chooseArr];
            if (self->picArr.count > 9) {
                [self ShowNewMsg:@"最多只能上传9张图片"];
                NSArray *arr = [self->picArr subarrayWithRange:NSMakeRange(0, 9)];
                self->picArr = [arr mutableCopy];
            }
            [self->collection_view reloadData];
        }
    }];
    
    //选择视频
//    [imagePickerVc setDidFinishPickingVideoHandle:^(UIImage *coverImage, PHAsset *asset) {
//
//    }];
    
    
    [self.navigationController presentViewController:imagePickerVc animated:YES completion:nil];
}

//删除图片
-(void)deletePicture:(UIButton *)sender{
    [self.view endEditing:YES];
    NSInteger tag = sender.tag - 2000;
    [picArr removeObjectAtIndex:tag];
    [collection_view reloadData];
}

//提交作品
-(void)upLoadFile{
    [service upLoadFile:picArr tag:8000];
}

#pragma mark - requestDelegate
-(void)getFinished:(NSDictionary *)obj tag:(long long)tag{
    LGTextView *textView = [self.view viewWithTag:10086];
    if (tag == 8000) {
        [fileList removeAllObjects];
        valuePicArr = [UpLoadImgModel mj_objectArrayWithKeyValuesArray:obj[@"list"]];
        for (int i = 0; i<valuePicArr.count; i++) {
            UpLoadImgModel *model = valuePicArr[i];
            [fileList addObject:model.url];
        }
        [service upLoadMyWorks:self.valueDic[@"id"] desc:textView.text fileList:fileList userId:NSUDGetToken tag:8001];
        
    }
    
    if (tag == 8001) {
        [self ShowNewMsg:@"作品提交成功"];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)getError:(NSError *)error tag:(long long)tag{
    [self ShowNewMsg:error.domain];
}

- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
